<template>
  <div class="deviceManage_detail form_detail_page" v-loading="isLoading">
    <one-title :title="$route.query.id ? '设备台账详情' : '设备台账新增'" @refreshData="refresh"></one-title>
    <el-form ref="listForm" :model="detailData" :rules="rules" v-if="!isEmpty&&!isLoading" class="fixed_top_56">
      <two-title title="基本信息"></two-title>
      <div class="from_panel">
        <div class="form_col form_col_left">
          <el-form-item class="form_item" label="工厂名称:" prop="factoryId">
            <div class="input_wapper">
              <el-select v-model.trim="detailData.factoryId" disabled @change="factorySelect" size="small" filterable
                         placeholder="请选择工厂名称">
                <el-option
                  v-for="item in treeList"
                  :key="item.id"
                  :label="item.text"
                  :value="item.id">
                </el-option>
              </el-select>
            </div>
            <div class="clear_panel"></div>
          </el-form-item>
          <el-form-item class="form_item" label="车间名称:" prop="workshopId">
            <div class="input_wapper">
              <el-select v-model.trim="detailData.workshopId" disabled @change="workshopSelect" size="small" filterable
                         placeholder="请先选择工厂名称">
                <el-option
                  v-for="item in workshop"
                  :key="item.id"
                  :label="item.text"
                  :value="item.id">
                </el-option>
              </el-select>
            </div>
          </el-form-item>
          <el-form-item class="form_item" label="设备编号:" prop="number">
            <div class="input_wapper">
              <el-input size="small"
                        :disabled="detailData.deviceStatusValue === 'Abandoned'"
                        placeholder="请输入设备编号"
                        v-model.trim="detailData.number"
                        clearable>
              </el-input>
            </div>
          </el-form-item>
          <el-form-item class="form_item" label="设备名称:" prop="name">
            <div class="input_wapper">
              <el-input size="small"
                        :disabled="detailData.deviceStatusValue === 'Abandoned'"
                        placeholder="请输入设备名称"
                        v-model.trim="detailData.name"
                        clearable>
              </el-input>
            </div>
          </el-form-item>
          <el-form-item class="form_item" label="设备序列号:" prop="deviceSerialNumber">
            <div class="input_wapper">
              <el-input size="small"
                        :disabled="detailData.deviceStatusValue === 'Abandoned'"
                        placeholder="请输入设备序列号"
                        v-model.trim="detailData.deviceSerialNumber"
                        clearable>
              </el-input>
            </div>
          </el-form-item>
        </div>
        <div class="form_col form_col_right">
          <el-form-item class="form_item" label="设备型号:" prop="deviceModelNumber">
            <div class="input_wapper">
              <el-input size="small"
                        :disabled="detailData.deviceStatusValue === 'Abandoned'"
                        placeholder="请输入设备型号"
                        v-model.trim="detailData.deviceModelNumber"
                        clearable>
              </el-input>
            </div>
          </el-form-item>
          <el-form-item class="form_item" label="设备规格:" prop="deviceSpec">
            <div class="input_wapper">
              <el-input size="small"
                        :disabled="detailData.deviceStatusValue === 'Abandoned'"
                        placeholder="请输入设备规格"
                        v-model.trim="detailData.deviceSpec"
                        clearable>
              </el-input>
            </div>
          </el-form-item>
          <el-form-item class="form_item" label="功率:" prop="devicePower">
            <div class="input_wapper">
              <el-input size="small"
                        :disabled="detailData.deviceStatusValue === 'Abandoned'"
                        placeholder="请输入功率"
                        v-model.trim="detailData.devicePower"
                        clearable>
              </el-input>
            </div>
          </el-form-item>
        </div>
        <div class="clear_panel"></div>
      </div>
      <two-title title="制造信息"></two-title>
      <div class="from_panel">
        <div class="form_col form_col_left">
          <el-form-item class="form_item" label="制造厂家:" prop="manufacturer">
            <div class="input_wapper">
              <el-input size="small"
                        :disabled="detailData.deviceStatusValue === 'Abandoned'"
                        placeholder="请输入制造厂家"
                        v-model.trim="detailData.manufacturer"
                        clearable>
              </el-input>
            </div>
          </el-form-item>
          <el-form-item class="form_item" label="出厂日期:" prop="manufactureDate">
            <div class="input_wapper">
              <el-date-picker
                :disabled="detailData.deviceStatusValue === 'Abandoned'"
                v-model="detailData.manufactureDate"
                type="date"
                :clearable="false"
                placeholder="请选择出厂日期"
                format="yyyy-MM-dd"
                value-format="yyyy-MM-dd HH:mm:ss"
                :picker-options="startPicker">
              </el-date-picker>
              <i class="date_icon"></i>
            </div>
          </el-form-item>
          <el-form-item class="form_item" label="投用日期:" prop="useDate">
            <div class="input_wapper">
              <el-date-picker
                :disabled="detailData.deviceStatusValue === 'Abandoned'"
                v-model="detailData.useDate"
                type="date"
                :clearable="false"
                placeholder="请选择投用日期"
                format="yyyy-MM-dd"
                value-format="yyyy-MM-dd HH:mm:ss"
                :picker-options="endPicker">
              </el-date-picker>
              <i class="date_icon"></i>
            </div>
          </el-form-item>
          <el-form-item class="form_item" label="使用寿命:" prop="deviceLifetime">
            <div class="input_wapper">
              <el-input size="small"
                        :disabled="detailData.deviceStatusValue === 'Abandoned'"
                        placeholder="请输入使用寿命"
                        v-model.trim="detailData.deviceLifetime"
                        clearable>
                <template slot="append">年</template>
              </el-input>
            </div>
          </el-form-item>
          <!--<el-form-item class="form_item" label="保养日期:" prop="maintainDate">
            <div class="input_wapper">
              <el-date-picker
                v-model="detailData.maintainDate"
                type="date"
                placeholder="选择保养日期"
                format="yyyy-MM-dd"
                value-format="yyyy-MM-dd HH:mm:ss">
              </el-date-picker>
              <i class="date_icon"></i>
            </div>
          </el-form-item>-->
          <el-form-item class="form_item" label="保养周期:" prop="maintainPeriod">
            <div class="input_wapper">
              <el-input size="small"
                        :disabled="detailData.deviceStatusValue === 'Abandoned'"
                        placeholder="请输入保养周期"
                        v-model.trim="detailData.maintainPeriod"
                        clearable>
                <template slot="append">月</template>
              </el-input>
            </div>
          </el-form-item>
          <el-form-item class="form_item" label=" ">
            <label></label>
            <div class="input_wapper mes_btn">
              <el-button type="primary" @click="save" :disabled="detailData.deviceStatusValue === 'Abandoned'">保存</el-button>
              <el-button @click="cancel">取消</el-button>
            </div>
          </el-form-item>
        </div>
        <div class="form_col form_col_right">
          <el-form-item class="form_item" label="所在位置:" prop="location">
            <div class="input_wapper">
              <el-input size="small"
                        :disabled="detailData.deviceStatusValue === 'Abandoned'"
                        placeholder="请输入所在位置"
                        v-model.trim="detailData.location"
                        clearable>
              </el-input>
            </div>
          </el-form-item>
          <el-form-item class="form_item" label="备注:" prop="remarks">
            <div class="input_wapper text_area">
              <el-input size="small" type="textarea"
                        :disabled="detailData.deviceStatusValue === 'Abandoned'"
                        :autosize="{ minRows: 2, maxRows: 4}"
                        placeholder="请输入内容"
                        v-model="detailData.remarks"
                        maxlength="255"></el-input>
              <span class="text_length" :class="{'disabled_text': detailData.deviceStatusValue === 'Abandoned'}">{{detailData.remarks ? detailData.remarks.length : 0}}/255</span>
            </div>
          </el-form-item>
        </div>
      </div>
    </el-form>
    <empty-page v-if="isEmpty&&!isLoading"></empty-page>
  </div>
</template>

<script>
import TwoTitle from '@/components/TwoTitle'
import tree from '@/utils/dataParse.js'
import EmptyPage from '@/components/EmptyPage'

export default {
  name: 'DeviceManageDetail',
  data() {
    return {
      // 是否为空数据
      isEmpty: false,
      //  加载中
      isLoading: true,
      // 开始监听数据
      startWatch: false,
      // 表单格式验证
      rules: {
        factoryId: [
          {required: true, message: '缺少工厂信息', trigger: 'blur'}
        ],
        workshopId: [
          {required: true, message: '缺少车间信息', trigger: 'blur'}
        ],
        number: [
          {required: true, message: '请输入设备编号', trigger: 'blur'},
          {max: 20, message: '设备编号长度不能超过20字符', trigger: 'blur'}
        ],
        name: [
          {required: true, message: '请输入设备名称', trigger: 'blur'},
          {max: 100, message: '设备名称长度不能超过100字符', trigger: 'blur'}
        ],
        deviceLifetime: [
          {validator: this.isPosInteger, message: '使用寿命必须是正整数', trigger: 'blur'}
        ],
        maintainPeriod: [
          {validator: this.isPosInteger, message: '保养周期必须是正整数', trigger: 'blur'}
        ],
        devicePower: [
          {validator: this.isDouble, message: '功率必须是正数，且最多保留两位小数', trigger: 'blur'}
        ],
        deviceSerialNumber: [
          {required: true, message: '请输入设备序列号', trigger: 'blur'},
          {max: 100, message: '设备序列号长度不能超过100字符', trigger: 'blur'}
        ],
        deviceModelNumber: [
          {max: 100, message: '设备型号长度不能超过100字符', trigger: 'blur'}
        ],
        deviceSpec: [
          {max: 100, message: '设备规格长度不能超过100字符', trigger: 'blur'}
        ],
        manufacturer: [
          {max: 100, message: '制造厂家长度不能超过100字符', trigger: 'blur'}
        ],
        location: [
          {max: 100, message: '所在位置长度不能超过100字符', trigger: 'blur'}
        ],
        remarks: [
          {max: 255, message: '备注长度不能超过255字符', trigger: 'blur'}
        ]
      }
    }
  },
  components: {
    TwoTitle,
    EmptyPage
  },
  watch: {
    detailData: {
      // 监听startWatch的时候判断当前页面是否有变化
      handler() {
        if (this.startWatch) {
          this.$store.commit('SetHasDetailChange', true)
        }
      },
      deep: true
    }
  },
  computed: {
    // 详情数据
    detailData() {
      const obj = this.$store.state.deviceManage.detailData
      return obj
    },
    // 获取树形数据
    treeList() {
      return this.$store.state.treeList
    },
    // 工厂id
    factoryId() {
      return this.$store.state.userInfo.factoryId || ''
    },
    // 车间id
    workshopId() {
      return this.$store.state.userInfo.workshopId || ''
    },
    // 获取工厂名称
    workshop() {
      return tree.getChildren(this.treeList, this.detailData.factoryId)
    },
    // 获取车间名称
    workgroup() {
      return tree.getChildren(this.workshop, this.detailData.workshopId)
    },
    // 设备"正常"状态ID(有状态id保存时参数为原有状态id,没有默认传递状态为"正常")
    deviceStatusId() {
      if (this.detailData.deviceStatusId) {
        return this.detailData.deviceStatusId
      } else {
        let list = this.$store.state.dict.DeviceStatus.labels || []
        let item = list.find((item) => item.value === 'Normal')
        return item ? item.id : ''
      }
    },
    // 出厂日期配置
    startPicker() {
      return {
        disabledDate: (time) => {
          return time > new Date(this.detailData.useDate)
        }
      }
    },
    // 投用日期配置
    endPicker() {
      return {
        disabledDate: (time) => {
          return time < new Date(this.detailData.manufactureDate)
        }
      }
    },
  },
  mounted() {
    this.refresh()
    this.detailData.factoryId = this.factoryId
    this.detailData.workshopId = this.workshopId
  },
  methods: {
    // 详情页面初始化
    refresh() {
      this.isLoading = true
      this.startWatch = false
      Promise.all([this.getDetail(), this.getTreeList()]).then(() => {
        this.isLoading = false
      }).catch(() => {
        this.isLoading = false
      })
    },
    // 获取详情
    getDetail() {
      let id = this.$route.query.id
      let postData = {
        method: 'get',
        module: 'deviceManage',
        state: 'detailData',
        url: 'a/device/device/get/' + id
      }
      if (!id) {
        postData.clean = true
      }
      return this.$store.dispatch('saveData', postData).then((res) => {
        this.startWatch = true
        if (id && !res) {
          this.isEmpty = true
        }
      }).catch(() => {
        this.isEmpty = true
      })
    },
    // 初始化树形结构数据
    getTreeList() {
      return this.$store.dispatch('getTreeList')
    },
    /**
     * 工厂选择，并获取车间列表
     * @param value
     */
    factorySelect(value) {
      this.$store.dispatch('setWorkgroupValue', '')
    },
    /**
     * 车间选择
     * @param value
     */
    workshopSelect(value) {
      this.$store.dispatch('setWorkgroupValue', value)
    },
    // 是否是正整数
    isPosInteger(rule, num, callback) {
      if (num) {
        if (!/^[0-9]*[1-9][0-9]*$/.test(num)) {
          callback(new Error(rule.message))
        } else {
          callback()
        }
      } else {
        callback()
      }
    },
    // 是否正整数或者两位小数
    isDouble(rule, num, callback) {
      if (num) {
        if (!/^\+?(\d*\.\d{1,2})$/.test(num) && !/^[0-9]*[1-9][0-9]*$/.test(num)) {
          callback(new Error(rule.message))
        } else {
          callback()
        }
      } else {
        callback()
      }
    },
    // 保存
    save() {
      if (this.saveState === false) return
      this.$refs['listForm'].validate((valid) => {
        if (valid) {
          this.isLoading = true
          this.detailData.deviceStatusId = this.deviceStatusId
          this.detailData.devicePower = this.detailData.devicePower || 0
          this.detailData.deviceLifetime = this.detailData.deviceLifetime || 0
          this.detailData.maintainPeriod = this.detailData.maintainPeriod || 0
          let postData = {
            method: 'post',
            url: 'a/device/device/saveuniquenumber',
            data: this.detailData,
            noCommit: true
          }
          let $route = this.$route
          this.$store.dispatch('saveData', postData).then(() => {
            this.saveSuccess($route)
          }).catch(() => {
            this.saveState = true
          }).finally(() => {
            this.isLoading = false
          })
        } else {
          return false
        }
      })
    },
    // 保存成功回调
    saveSuccess($route) {
      this.$message({
        message: '保存成功',
        type: 'success',
        duration: 500,
        center: true,
        onClose: () => {
          this.$store.commit('SetHasDetailChange', false)
          this.$store.dispatch('delCurrentViews', $route).then(() => {
            this.$router.push('/deviceManage')
            this.$store.commit('SetRefresh', true) // 跳转到列表页刷新
          })
        }
      })
    },
    // 取消
    cancel() {
      let $route = this.$route
      this.backToList().then(() => {
        this.$store.dispatch('delCurrentViews', $route).then(() => {
          this.$router.push('/deviceManage')
        })
      })
    }
  }
}
</script>

<style scoped lang="less">
  .deviceManage_detail {
    .fixed_top_56 {
      padding-bottom: 10px;
    }
    .disabled_text{
      background-color: #f5f7fa!important;
      cursor:not-allowed;
    }
  }
</style>
